package Work;
import Work.Product;
import Work.ProductService;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;

public class EStoreServer {
    private final ProductService productService = new ProductService();

    public static void main(String[] args) {
        EStoreServer server = new EStoreServer();
        server.start();
    }

    private void start() {
        try (ServerSocket serverSocket = new ServerSocket(8888)) {
            System.out.println("服务器已启动，监听端口8888...");
            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("接收到客户端连接：" + clientSocket.getInetAddress());
                handleClient(clientSocket);
            }
        } catch (Exception e) {
            System.err.println("服务器异常：" + e.getMessage());
        }
    }

    private void handleClient(Socket clientSocket) {
        try (
                ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream());
                ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream())
        ) {
            // 读取客户端请求
            String request = (String) ois.readObject();
            System.out.println("收到请求：" + request);

            // 处理请求并返回数据
            if ("GET_ALL_PRODUCTS".equals(request)) {
                List<Product> products = productService.getAllProducts();
                oos.writeObject(products);
                oos.flush();
                System.out.println("已返回商品列表（共" + products.size() + "条）");
            } else {
                oos.writeObject("不支持的请求：" + request);
                oos.flush();
            }
        } catch (Exception e) {
            System.err.println("处理客户端请求异常：" + e.getMessage());
        } finally {
            try {
                clientSocket.close();
                System.out.println("客户端连接已关闭");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
